<template>
  <div class="container mx-auto px-4 py-6">
    <div class="flex justify-between items-center mb-6">
      <h2 class="text-2xl font-semibold text-gray-800">物品领用</h2>
      <button @click="$router.back()" class="flex items-center px-4 py-2 bg-gray-500 text-white rounded-md hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2">
        <ArrowLeftIcon class="h-5 w-5 mr-2" />
        返回
      </button>
    </div>

    <form @submit.prevent="handleSubmit" class="space-y-6">
      <!-- 基本信息 -->
      <div class="bg-white rounded-xl shadow-lg p-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">基本信息</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label for="laboratory" class="block text-sm font-medium text-gray-700 mb-2">所属实验室 *</label>
            <select id="laboratory" v-model="form.laboratory" required class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
              <option value="">请选择实验室</option>
              <option value="计算机实验室A">计算机实验室A</option>
              <option value="计算机实验室B">计算机实验室B</option>
              <option value="化学实验室">化学实验室</option>
              <option value="生物实验室">生物实验室</option>
              <option value="物理实验室">物理实验室</option>
            </select>
          </div>
          <div>
            <label for="applicationType" class="block text-sm font-medium text-gray-700 mb-2">申请类型 *</label>
            <select id="applicationType" v-model="form.applicationType" required class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
              <option value="">请选择申请类型</option>
              <option value="PLANNED">计划内申请</option>
              <option value="UNPLANNED">计划外申请</option>
            </select>
          </div>
          <div>
            <label for="receiverName" class="block text-sm font-medium text-gray-700 mb-2">领用人 *</label>
            <input type="text" id="receiverName" v-model="form.receiverName" required placeholder="请输入领用人姓名" class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
          </div>
          <div>
            <label for="receiverPhone" class="block text-sm font-medium text-gray-700 mb-2">联系电话 *</label>
            <input type="tel" id="receiverPhone" v-model="form.receiverPhone" required placeholder="请输入联系电话" class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
          </div>
        </div>
      </div>

      <!-- 领用物品 -->
      <div class="bg-white rounded-xl shadow-lg p-6">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-semibold text-gray-800">领用物品</h3>
          <button type="button" @click="addItem" class="flex items-center px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">
            <PlusIcon class="h-5 w-5 mr-2" />
            添加物品
          </button>
        </div>

        <div v-if="form.items.length === 0" class="text-center py-8 text-gray-500">
          <CubeIcon class="h-12 w-12 mx-auto mb-4 text-gray-300" />
          <p>暂无领用物品，请点击"添加物品"按钮添加</p>
        </div>

        <div v-else class="space-y-4">
          <div v-for="(item, index) in form.items" :key="index" class="border border-gray-200 rounded-lg p-4">
            <div class="flex justify-between items-start mb-4">
              <h4 class="text-md font-medium text-gray-700">物品 {{ index + 1 }}</h4>
              <button type="button" @click="removeItem(index)" class="text-red-600 hover:text-red-800">
                <TrashIcon class="h-5 w-5" />
              </button>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <label :for="`itemName_${index}`" class="block text-sm font-medium text-gray-700 mb-2">物品名称 *</label>
                <input type="text" :id="`itemName_${index}`" v-model="item.itemName" required placeholder="请输入物品名称" class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
              </div>
              <div>
                <label :for="`specification_${index}`" class="block text-sm font-medium text-gray-700 mb-2">规格型号</label>
                <input type="text" :id="`specification_${index}`" v-model="item.specification" placeholder="请输入规格型号" class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
              </div>
              <div>
                <label :for="`unit_${index}`" class="block text-sm font-medium text-gray-700 mb-2">单位 *</label>
                <select :id="`unit_${index}`" v-model="item.unit" required class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                  <option value="">请选择单位</option>
                  <option value="个">个</option>
                  <option value="包">包</option>
                  <option value="盒">盒</option>
                  <option value="支">支</option>
                  <option value="本">本</option>
                  <option value="张">张</option>
                  <option value="套">套</option>
                </select>
              </div>
              <div>
                <label :for="`quantity_${index}`" class="block text-sm font-medium text-gray-700 mb-2">申请数量 *</label>
                <input type="number" :id="`quantity_${index}`" v-model.number="item.quantity" required min="1" placeholder="请输入申请数量" class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
              </div>
              <div>
                <label :for="`purpose_${index}`" class="block text-sm font-medium text-gray-700 mb-2">用途说明 *</label>
                <input type="text" :id="`purpose_${index}`" v-model="item.purpose" required placeholder="请输入用途说明" class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 其他信息 -->
      <div class="bg-white rounded-xl shadow-lg p-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">其他信息</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label for="contactPerson" class="block text-sm font-medium text-gray-700 mb-2">联系人</label>
            <input type="text" id="contactPerson" v-model="form.contactPerson" placeholder="请输入联系人姓名" class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
          </div>
          <div>
            <label for="contactPhone" class="block text-sm font-medium text-gray-700 mb-2">联系电话</label>
            <input type="tel" id="contactPhone" v-model="form.contactPhone" placeholder="请输入联系电话" class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
          </div>
          <div class="md:col-span-2">
            <label for="remarks" class="block text-sm font-medium text-gray-700 mb-2">备注</label>
            <textarea id="remarks" v-model="form.remarks" rows="3" placeholder="请输入备注信息" class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"></textarea>
          </div>
        </div>
      </div>

      <!-- 提交按钮 -->
      <div class="flex justify-end space-x-4">
        <button type="button" @click="$router.back()" class="px-6 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2">
          取消
        </button>
        <button type="submit" :disabled="loading" class="px-6 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed">
          <span v-if="loading">提交中...</span>
          <span v-else>提交申请</span>
        </button>
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import {
  ArrowLeftIcon,
  PlusIcon,
  TrashIcon,
  CubeIcon,
} from '@heroicons/vue/24/outline'

const router = useRouter()
const loading = ref(false)

const form = reactive({
  laboratory: '',
  applicationType: '',
  receiverName: '',
  receiverPhone: '',
  contactPerson: '',
  contactPhone: '',
  remarks: '',
  items: []
})

// 添加物品
const addItem = () => {
  form.items.push({
    itemName: '',
    specification: '',
    unit: '',
    quantity: 1,
    purpose: ''
  })
}

// 删除物品
const removeItem = (index) => {
  form.items.splice(index, 1)
}

// 表单验证
const validateForm = () => {
  if (!form.laboratory) {
    showMessage('请选择所属实验室', 'error')
    return false
  }
  if (!form.applicationType) {
    showMessage('请选择申请类型', 'error')
    return false
  }
  if (!form.receiverName) {
    showMessage('请输入领用人姓名', 'error')
    return false
  }
  if (!form.receiverPhone) {
    showMessage('请输入联系电话', 'error')
    return false
  }
  if (form.items.length === 0) {
    showMessage('请至少添加一个领用物品', 'error')
    return false
  }
  
  for (let i = 0; i < form.items.length; i++) {
    const item = form.items[i]
    if (!item.itemName) {
      showMessage(`请填写第${i + 1}个物品的名称`, 'error')
      return false
    }
    if (!item.unit) {
      showMessage(`请选择第${i + 1}个物品的单位`, 'error')
      return false
    }
    if (!item.quantity || item.quantity <= 0) {
      showMessage(`请填写第${i + 1}个物品的有效数量`, 'error')
      return false
    }
    if (!item.purpose) {
      showMessage(`请填写第${i + 1}个物品的用途说明`, 'error')
      return false
    }
  }
  
  return true
}

// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) {
    return
  }
  
  try {
    loading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    showMessage('领用申请提交成功！', 'success')
    
    // 重置表单
    Object.assign(form, {
      laboratory: '',
      applicationType: '',
      receiverName: '',
      receiverPhone: '',
      contactPerson: '',
      contactPhone: '',
      remarks: '',
      items: []
    })
    
    // 跳转到领用记录页面
    router.push('/consumable-receive')
    
  } catch (error) {
    console.error('提交失败:', error)
    showMessage('提交失败，请重试', 'error')
  } finally {
    loading.value = false
  }
}

// 简单消息提示函数
const showMessage = (message, type = 'info') => {
  const messageEl = document.createElement('div')
  messageEl.className = `fixed top-4 right-4 px-6 py-3 rounded-lg text-white z-50 ${
    type === 'success' ? 'bg-green-500' :
    type === 'warning' ? 'bg-yellow-500' :
    type === 'error' ? 'bg-red-500' :
    'bg-blue-500'
  }`
  messageEl.textContent = message
  document.body.appendChild(messageEl)

  setTimeout(() => {
    if (document.body.contains(messageEl)) {
      document.body.removeChild(messageEl)
    }
  }, 3000)
}
</script>
